package hoowin.common.dao.springImp;

import java.sql.ResultSet;
import java.sql.SQLException;
import hoowin.common.dao.IFileItemDao;
import hoowin.common.model.FileItem;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class FileItemDao extends JdbcDaoSupport implements IFileItemDao {

	@Override
	public FileItem getFileItemById(int id) {
		String sql = "select * from basic_files where id="+id;
		return (FileItem)super.getJdbcTemplate().queryForObject(sql, new FileItemRowMapper());
	}

	class FileItemRowMapper implements RowMapper<Object>{
		@Override
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			FileItem item = new FileItem();
			item.setId(rs.getInt("id"));
			item.setItemContentType(rs.getString("content_type"));
			item.setItemFileName(rs.getString("name"));
			item.setKey(rs.getString("passkey"));
			item.setSize(rs.getInt("size"));
			return item;
		}	
	}

	@Override
	public int saveFileItem(FileItem fi) {
		String sql = "insert into basic_files (id, name, content_type, size, passkey) values (null, ?, ?, ?, ?)";
		if(super.getJdbcTemplate().update(sql, fi.getItemFileName(), fi.getItemContentType(), fi.getSize(), fi.getKey())>0){
			return super.getJdbcTemplate().queryForInt("select last_insert_id()");
		}else return 0;
	}
}
